/**
 * Created by forcht on 2018/5/19.
 */
public class Solution {
    public boolean exist(char[][] board, String word) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (dfs(board, word, i, j, 0)) return true;
            }
        }
        return false;
    }

    boolean dfs(char[][] board, String word, int i, int j, int cur) {
        if (board[i][j] == word.charAt(cur)) {
            if (cur == word.length()-1) return true;
            int n = board.length, m = board[0].length;
            char c = board[i][j];
            board[i][j] = '*';
            boolean flag=false;
            if ((j < m - 1 && dfs(board, word, i, j + 1, cur + 1)) ||
                    (j > 0 && dfs(board, word, i, j - 1, cur + 1)) ||
                    (i > 0 && dfs(board, word, i - 1, j, cur+1)) ||
                    (i < n - 1 && dfs(board, word, i + 1, j, cur+1))) {
                flag=true;
            }
            board[i][j] = c;
            return flag;
        }
        return false;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        char[][] board = {
                {'a', 'a'}
        };
        System.out.println(solution.exist(board, "aaa"));
    }
}
